package com.springapp.mvc.dao;

import com.springapp.mvc.entity.Post;
import com.springapp.mvc.entity.UserPost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by dbychkov on 26.12.2014.
 */
@Component
public class PostsDaoImpl implements PostsDao{

    @Autowired
    private JdbcTemplate template;

    @Override
    public List<UserPost> getPosts(Long start, Long end) {
        String queryText =  "SELECT p.id post_id, " +
                "p.date_created postDate, " +
                "p.post_text postText, " +
                "p.image_hash_id imageHashId, " +
                "u.id userId, " +
                "u.name userName " +
                "FROM posts p " +
                "INNER JOIN users u ON p.user_id = u.id " +
                "ORDER BY p.id DESC LIMIT ?, ? ";
        return template.query(queryText, Mappers.USER_POST_MAPPER, start, end);
    }

    @Override
    public void addPost(Long userId, String postText, String fileUniqueName) {
        String queryText = "INSERT INTO posts(user_id, post_text, image_hash_id) values(?, ?, ?)";
        template.update(queryText, userId, postText, fileUniqueName);
    }

    @Override
    public void deleteMessage(Long postId) {
        template.update("DELETE FROM comments WHERE post_id=?", postId);
        template.update("DELETE FROM posts WHERE id=?", postId);
    }

    @Override
    public void editMessage(Long postId, String newText) {
        template.update("UPDATE posts SET POST_TEXT=? WHERE ID=?", newText, postId);
    }

    @Override
    public Post getPostById(Long postId) {
        String q =  "SELECT * FROM posts WHERE ID = ?";
        return template.queryForObject(q, Mappers.POST_MAPPER,postId);
    }
}
